<template>
  <div class="goods_add">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert title="添加商品信息" type="info" show-icon center :closable="false"></el-alert>
      <!--
         space     每个 step 的间距，不填写将自适应间距。支持百分比。
         active    设置当前激活步骤  number
         finish-status  设置结束步骤的状态
         align-center   居中对齐
      -->
      <el-steps finish-status="success" align-center :active="Number(activeIndex)">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef">
        <el-tabs tab-position="left" v-model="activeIndex" :before-leave="handleTab">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number" min="0"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number" min="0"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number" min="0"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat" label-width="80px">
              <el-cascader
                expand-trigger="hover"
                :options="goodsCateList"
                v-model="addForm.goods_cat"
                :props="casProps"
                @change="handleChange"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item v-for="(item,index) in manyList" :key="index" :label="item.attr_name">
              <el-checkbox-group v-model="item.attr_vals" size="mini">
                <el-checkbox v-for="(ite,ind) in item.attr_vals" :key="ind" :label="ite" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item v-for="(item,index) in onlyList" :key="index" :label="item.attr_name">
              <el-checkbox-group v-model="item.attr_vals" size="mini">
                <el-checkbox v-for="(ite,ind) in item.attr_vals" :key="ind" :label="ite" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :action="uploadUrl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              :headers="uploadHeaders"
              list-type="picture"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button type="primary" @click="addShop" class="btn">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <el-dialog title="图片预览" :visible.sync="picturePreview" width="50%">
      <img :src="picPath" alt="" class="img">
    </el-dialog>
  </div>
</template>

<script>
import * as goods from '../../api/goods'

import { quillEditor } from 'vue-quill-editor' // 调用编辑器
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

import _ from 'lodash'

export default {
  components: { quillEditor },
  data () {
    return {
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        goods_introduce: '',
        pics: [],
        attrs: []
      },
      goodsCateList: [],
      casProps: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      addFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'blur' }
        ]
      },
      activeIndex: '0',
      activeSel: 'many',
      manyList: [],
      onlyList: [],
      uploadUrl: 'http://localhost:8888/api/private/v1/upload',
      uploadHeaders: { Authorization: this.$store.getters.getToken },
      picturePreview: false,
      picPath: ''
    }
  },
  computed: {
    id () {
      return this.addForm.goods_cat.length !== 3
        ? null
        : this.addForm.goods_cat[this.addForm.goods_cat.length - 1]
    }
  },
  created () {
    this.getGoodsCateList()
  },
  methods: {
    async getGoodsCateList () {
      const { data: res } = await goods.getGoodsCateList()
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.goodsCateList = res.data
    },
    handleChange () {
      if (this.addForm.goods_cat.length !== 3) {
        return (this.addForm.goods_cat = [])
      }
    },
    handleTab (index) {
      if (this.addForm.goods_cat.length !== 3) {
        this.$message.warning('请选择商品分类')
        return false
      }
      console.log(index)
      if (index === '1') {
        this.activeSel = 'many'
        this.getParamsList()
      } else if (index === '2') {
        this.activeSel = 'only'
        this.getParamsList()
      }
    },
    async getParamsList () {
      const { data: res } = await goods.getParamsList(this.id, this.activeSel)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals
          ? item.attr_vals.replace(/,/g, ' ').split(' ')
          : []
      })
      if (this.activeSel === 'many') {
        this.manyList = res.data
      } else if (this.activeSel === 'only') {
        this.onlyList = res.data
      }
      console.log(res)
    },
    handlePreview (file) {
      console.log(file)
      this.picturePreview = true
      this.picPath = file.url
    },
    handleRemove (file, filelist) {
      this.addForm.pics = filelist.map(item => {
        return { pic: item.response.data.tmp_path }
      })
      console.log(this.addForm.pics)
    },
    handleSuccess (res) {
      console.log(res)
      const picObj = { pic: res.data.tmp_path }
      this.addForm.pics.push(picObj)
      console.log(this.addForm.pics)
    },
    // 添加商品处理参数
    addShop () {
      const postForm = _.cloneDeep(this.addForm)
      postForm.goods_cat = postForm.goods_cat.join(',')
      // 处理动态参数
      this.manyList.forEach(item => {
        const obj = {
          attr_id: item.attr_id,
          attr_value: item.attr_vals.join(',')
        }
        postForm.attrs.push(obj)
      })
      // 处理静态属性
      this.onlyList.forEach(item => {
        const obj = {
          attr_id: item.attr_id,
          attr_value: item.attr_vals.join(',')
        }
        postForm.attrs.push(obj)
      })
      this.postShop(postForm)
    },
    async postShop (params) {
      const { data: res } = await goods.postShop(params)
      if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.$router.push('/goods')
    }
  }
}
</script>

<style lang="less" scoped>
.el-steps {
  margin: 15px 0;
}
.goods_add/deep/.el-step__title {
  font-size: 13px;
}
.el-checkbox-group {
  clear: both;
  text-align: left;
}
.img{
  width: 100%;
  height: 100%;
}
.goods_add/deep/.ql-editor{
  min-height: 200px;
}
.btn{
  margin-top: 15px;
}
</style>
